import wxPay from '../wxtools/wxPaytools.js'
import alipayPay from '../alipaytools/alipayPaytools.js'

// 统一下单(直连支付模式)
function unifiedorder(params) {
	//params示例:
	/*
	let params = {
		orderId: orderId,
		openid: uni.getStorageSync(app.globalData.session.userKey),
		amount: price,
		amountFen: this.$mytools.regYuanToFen(price, 100),
		title: '商户充值',
		type: 2, //统一下单--直连支付模式，如：商户充值--下单
		remark: '备注:商户充值',
	}
	*/
	// #ifdef MP-WEIXIN
	console.log('MP-WEIXIN环境...');
	return new Promise((resolve, reject) => {
		wxPay.unifiedorder(params).then(res => {
			console.log('成功');
			resolve(res)
		}).catch(err => {
			console.log('失败');
			reject(err)
		})
	})
	// #endif
	// #ifdef MP-ALIPAY
	console.log('MP-ALIPAY环境....');
	return new Promise((resolve, reject) => {
		alipayPay.unifiedorder(params).then(res => {
			console.log('成功');
			resolve(res)
		}).catch(err => {
			console.log('失败');
			reject(err)
		})
	})
	// #endif
}

function businessRecharge(params) {
	// #ifdef MP-WEIXIN
	console.log('MP-WEIXIN环境...');
	return new Promise((resolve, reject) => {
		wxPay.businessRecharge(params).then(res => {
			console.log('成功');
			let param = {
				orderId: params.orderId,
				// 已支付:支付成功
				status: 1,
				pay_time: parseInt(new Date().getTime() / 1000),
				operateType: 2
			}
			updateOrderStausAndBusinessReserveAmount(param, params.amountFen)
			resolve(res)
		}).catch(err => {
			console.log('失败');
			let param = {
				orderId: params.orderId,
				// 支付失败
				status: 2,
				pay_time: parseInt(new Date().getTime() / 1000),
				operateType: 2,
				order_fail_reason: err.errMsg
			}
			updateOrderStausAndBusinessReserveAmount(param, params.amountFen)
			reject(err)
		})
	})
	// #endif
	// #ifdef MP-ALIPAY
	console.log('MP-ALIPAY环境....');
	return new Promise((resolve, reject) => {
		alipayPay.businessRecharge(params).then(res => {
			console.log('成功');
			let param = {
				orderId: params.orderId,
				// 支付宝状态为订单处理成功，并非支付成功
				status: 3,
				pay_time: parseInt(new Date().getTime() / 1000),
				operateType: 2
			}
			updateOrderStausAndBusinessReserveAmount(param, params.amountFen)
			resolve(res)
		}).catch(err => {
			console.log('失败');
			let param = {
				orderId: params.orderId,
				// 支付失败
				status: 2,
				pay_time: parseInt(new Date().getTime() / 1000),
				operateType: 2,
				order_fail_reason: err.errMsg
			}
			updateOrderStausAndBusinessReserveAmount(param, params.amountFen)
			reject(err)
		})
	})
	// #endif
}

function userWithdrawToCash(params) {
	// #ifdef MP-WEIXIN
	console.log('MP-WEIXIN环境...');
	return new Promise((resolve, reject) => {
		wxPay.userWithdrawToCash(params).then(res => {
			console.log('成功');
			// 提现成功后的操作
			afterUserWithdrawSuccess(uni.getStorageSync(app.globalData.session.userKey))
			resolve(res)
		}).catch(err => {
			console.log('失败');
			reject(err)
		})
	})
	// #endif
	// #ifdef MP-ALIPAY
	console.log('MP-ALIPAY环境....');
	return new Promise((resolve, reject) => {
		// todo lxw
		alipayPay.userWithdrawToCash(params).then(res => {
			console.log('成功');
			// 提现成功后的操作
			afterUserWithdrawSuccess(uni.getStorageSync(app.globalData.session.userKey))
			resolve(res)
		}).catch(err => {
			console.log('失败');
			reject(err)
		})
	})
	// #endif
}

function afterUserWithdrawSuccess(openid) {
	// todo lxw 用户成功提现后的操作：补贴。排队等
	// 补贴结束，取消排队和补贴
}

function updateOrderStausAndBusinessReserveAmount(param, amountFen) {
	const app = getApp()
	uniCloud.callFunction({
		name: 'zhy-order',
		data: param,
		success(r) {
			console.log('更新订单状态成功');
			if (param.status == 1) {
				// 支付完成才修改
				let businessReserveAmountData = {
					crud: 5,
					businessId: uni.getStorageSync(app.globalData.session.businessInfo).offlineBusinessId,
					amountFen: amountFen
				}
				console.log(JSON.stringify(businessReserveAmountData));
				uniCloud.callFunction({
					name: 'zhy-business-info-crud',
					data: businessReserveAmountData,
					success(businessReserveRes) {
						console.log('更新商户备付金成功');
					},
					fail(businessReserveRes) {
						console.log('更新商户备付金失败');
					}
				})
			} else {
				console.log('支付失败，不需要修改备付金');
			}
		},
		fail(err) {
			console.log('更新订单状态失败');
			console.log(JSON.stringify(err));
		}
	})
}

// 统一下单（服务商支付模式)
function partnerUnifiedorder(params) {
	//params示例:
	/*
	let params = {
		orderId: orderId,
		openid: uni.getStorageSync(app.globalData.session.userKey),
		amount: price,
		amountFen: this.$mytools.regYuanToFen(price, 100),
		title: '商户充值',
		type: 4, //服务商支付模式--下单
		remark: '备注:商户充值',
	}
	*/
	// #ifdef MP-WEIXIN
	console.log('MP-WEIXIN环境...');
	return new Promise((resolve, reject) => {
		wxPay.partnerUnifiedorder(params).then(res => {
			console.log('成功');
			resolve(res)
		}).catch(err => {
			console.log('失败');
			reject(err)
		})
	})
	// #endif
	// #ifdef MP-ALIPAY
	console.log('MP-ALIPAY环境....');
	return new Promise((resolve, reject) => {
		alipayPay.partnerUnifiedorder(params).then(res => {
			console.log('成功');
			resolve(res)
		}).catch(err => {
			console.log('失败');
			reject(err)
		})
	})
	// #endif
}

function partnerPay(params, profitSharingParam) {
	const app = getApp()
	// #ifdef MP-WEIXIN
	console.log('MP-WEIXIN环境...');
	return new Promise((resolve, reject) => {
		wxPay.partnerPay(params).then(res => {
			console.log('成功');
			let param = {
				orderId: params.orderId,
				// 已支付:支付成功
				status: 1,
				pay_time: parseInt(new Date().getTime() / 1000),
				operateType: 2
			}
			// 修改订单状态
			updateOrderStausAndBusinessReserveAmount(param, params.amountFen)
			// 请求分账
			let profitShareParam = {
				description: profitSharingParam.description, // 分账描述
				amountFen: params.amountFen, // 分账金额，单位：分
				orderId: profitSharingParam.orderId, // 商户分账单号，并非商户的订单号
				// 商户id
				offlineBusinessId: profitSharingParam.offlineBusinessId
			}
			wxPay.partnerProfitSharing(profitShareParam)
			resolve(res)
		}).catch(err => {
			console.log('失败');
			let param = {
				orderId: params.orderId,
				// 支付失败
				status: 2,
				pay_time: parseInt(new Date().getTime() / 1000),
				operateType: 2,
				order_fail_reason: err.errMsg
			}
			updateOrderStausAndBusinessReserveAmount(param, params.amountFen)
			reject(err)
		})
	})
	// #endif
	// #ifdef MP-ALIPAY
	console.log('MP-ALIPAY环境....');
	return new Promise((resolve, reject) => {
		alipayPay.partnerPay(params).then(res => {
			console.log('成功');
			let param = {
				orderId: params.orderId,
				// 支付宝状态为订单处理成功，并非支付成功
				status: 3,
				pay_time: parseInt(new Date().getTime() / 1000),
				operateType: 2
			}
			updateOrderStausAndBusinessReserveAmount(param, params.amountFen)
			resolve(res)
		}).catch(err => {
			console.log('失败');
			let param = {
				orderId: params.orderId,
				// 支付失败
				status: 2,
				pay_time: parseInt(new Date().getTime() / 1000),
				operateType: 2,
				order_fail_reason: err.errMsg
			}
			updateOrderStausAndBusinessReserveAmount(param, params.amountFen)
			reject(err)
		})
	})
	// #endif
}

module.exports = {
	// 下单
	unifiedorder,
	// 支付:商家充值
	businessRecharge,
	// 提现到零钱:用户提现
	userWithdrawToCash,
	// 服务商：分账统一下单
	partnerUnifiedorder,
	// 服务商支付（和businessRecharge基本一致）
	partnerPay
}